package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.management.aop.anno.CacheAble;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author: Enid
 * @date: 2025/10/17 16:33
 * @description:
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class RedisAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.qk.management.aop.anno.CacheAble)")
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object redisCache(ProceedingJoinPoint point) throws NoSuchMethodException {
        Object returnValue = null;
        String key = null;
        long expireTime = 0;
        TimeUnit timeUnit = null;
        try {

            Class<?> targetClass = point.getTarget().getClass();
            String name = point.getSignature().getName();
            Method method = targetClass.getMethod(name);
            CacheAble cacheAble = method.getAnnotation(CacheAble.class);

            String keyPrefix = cacheAble.KeyPrefix();
            key = point + "reportOverview";
            expireTime = cacheAble.ExpireTime();
            timeUnit = cacheAble.timeUnit();
            String jsonStr;
            jsonStr = redisTemplate.opsForValue().get(key);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());


            }
        } catch (Throwable e) {
            returnValue = Result.error("操作失败");
        }
        try {
            returnValue = point.proceed();
        } catch (Throwable e) {
            returnValue = Result.error("操作有问题");
        }


        try {
            String json = JSONUtil.toJsonStr(returnValue);
            redisTemplate.opsForValue().set(key, json, expireTime, timeUnit);
        } catch (Exception e) {
            log.error("redis服务异常", e);
        }

        return returnValue;
    }
}
